package com.jhm.bing_fa_rong_qi;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

// 一个简单的任务类，实现Delayed接口
class MyDelayedTask implements Delayed {
    private long executionTime; // 任务执行的时间

    public MyDelayedTask(long delay) {
        this.executionTime = System.currentTimeMillis() + delay;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(executionTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed other) {
        if (other instanceof MyDelayedTask) {
            return Long.compare(this.executionTime, ((MyDelayedTask) other).executionTime);
        }
        return 0;
    }

    @Override
    public String toString() {
        return "Task to be executed at: " + new java.util.Date(executionTime);
    }
}

public class DelayQueueExample {
    public static void main(String[] args) {
        DelayQueue<MyDelayedTask> queue = new DelayQueue<>();

        // 添加任务
        queue.put(new MyDelayedTask(3000)); // 3秒后执行的任务
        queue.put(new MyDelayedTask(1000)); // 1秒后执行的任务
        queue.put(new MyDelayedTask(2000)); // 2秒后执行的任务

        // 消费任务
        try {
            while (!Thread.currentThread().isInterrupted()) {
                MyDelayedTask task = queue.take(); // 取出并执行任务
                System.out.println("Executing task: " + task);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}